﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using ERP.Team.WarehouseManagement;
using ERP.ERPSystem.WarehouseManagement.Dto;
using ERP.Common.Results;

namespace ERP.ERPSystem.WarehouseManagement
{
    /// <summary>
    /// 仓储管理-采购入库服务类
    /// </summary>
    public class ProcurementwarehousingServices:ApplicationService, IProcurementwarehousingServices
    {
        private readonly IRepository<ProcurementwarehousingModel, int> _procurementwarehousingRepository;

        public ProcurementwarehousingServices(IRepository<ProcurementwarehousingModel, int> procurementwarehousingRepository)
        {
            _procurementwarehousingRepository = procurementwarehousingRepository;
        }

        /// <summary>
        /// 分页查询采购入库列表
        /// </summary>
        /// <param name="queryDto">查询条件</param>
        /// <returns>分页结果</returns>
        public async Task<APIPaging<ProcurementwarehousingDTO>> GetPagedListAsync(ProcurementwarehousingQueryDto queryDto)
        {
            try
            {
                APIPaging<ProcurementwarehousingDTO> pageList = new APIPaging<ProcurementwarehousingDTO>();
                var query = await _procurementwarehousingRepository.GetQueryableAsync();

                // 条件筛选
                query = query.WhereIf(!string.IsNullOrEmpty(queryDto.LnboundCode), 
                    m => m.LnboundCode.Contains(queryDto.LnboundCode));
                query = query.WhereIf(!string.IsNullOrEmpty(queryDto.LnboundName), 
                    m => m.LnboundName.Contains(queryDto.LnboundName));
                query = query.WhereIf(!string.IsNullOrEmpty(queryDto.VendorName), 
                    m => m.VendorName.Contains(queryDto.VendorName));
                query = query.WhereIf(!string.IsNullOrEmpty(queryDto.ProcurementNumber), 
                    m => m.ProcurementNumber.Contains(queryDto.ProcurementNumber));
                query = query.WhereIf(queryDto.LnboundDateStart.HasValue, 
                    m => m.LnboundDate >= queryDto.LnboundDateStart.Value);
                query = query.WhereIf(queryDto.LnboundDateEnd.HasValue, 
                    m => m.LnboundDate <= queryDto.LnboundDateEnd.Value);

                var totalCount = query.Count();
                
                // 确保分页参数有效
                var page = Math.Max(1, queryDto.Page);
                var limit = Math.Max(1, Math.Min(100, queryDto.Limit)); // 限制每页最大100条
                
                var entities = query.OrderByDescending(m => m.Id)
                    .Skip((page - 1) * limit)
                    .Take(limit)
                    .ToList();

                // 转换为DTO
                var dtoList = entities.Select(e => new ProcurementwarehousingDTO
                {
                    Id = e.Id,
                    LnboundCode = e.LnboundCode,
                    LnboundName = e.LnboundName,
                    VendorName = e.VendorName,
                    LnboundDate = e.LnboundDate,
                    ProcurementNumber = e.ProcurementNumber,
                    TotalAmount = e.TotalAmount,
                    DocumentStatus = e.DocumentStatus
                }).ToList();

                pageList.PageCount = totalCount; // 总记录数
                pageList.ListDate = dtoList;
                pageList.PageIndex = Convert.ToInt32(Math.Ceiling(totalCount * 1.0 / limit)); // 总页数
                
                return pageList;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 根据ID获取采购入库详情
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>详情信息</returns>
        public async Task<ProcurementwarehousingDTO> GetByIdAsync(int id)
        {
            try
            {
                var entity = await _procurementwarehousingRepository.GetAsync(e => e.Id == id);
                if (entity == null) return null;

                return new ProcurementwarehousingDTO
                {
                    Id = entity.Id,
                    LnboundCode = entity.LnboundCode,
                    LnboundName = entity.LnboundName,
                    VendorName = entity.VendorName,
                    LnboundDate = entity.LnboundDate,
                    ProcurementNumber = entity.ProcurementNumber,
                    TotalAmount = entity.TotalAmount,
                    DocumentStatus = entity.DocumentStatus
                };
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 新增采购入库
        /// </summary>
        /// <param name="createDto">新增数据</param>
        /// <returns>操作结果</returns>
        public async Task<bool> CreateAsync(ProcurementwarehousingCreateDto createDto)
        {
            try
            {
                var entity = new ProcurementwarehousingModel
                {
                    LnboundCode = GenerateInboundCode(), // 自动生成编号
                    LnboundName = createDto.LnboundName,
                    VendorName = createDto.VendorName,
                    LnboundDate = createDto.LnboundDate,
                    ProcurementNumber = createDto.ProcurementNumber,
                    TotalAmount = createDto.TotalAmount,
                    DocumentStatus = createDto.DocumentStatus
                };

                var result = await _procurementwarehousingRepository.InsertAsync(entity);
                return result != null;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 生成入库单编号
        /// </summary>
        /// <returns>入库单编号</returns>
        public async Task<string> GenerateInboundCodeAsync()
        {
            // 生成格式：R + 年月日 + 6位序号，例如：R20250623000001
            var datePrefix = DateTime.Now.ToString("yyyyMMdd");
            var prefix = $"R{datePrefix}";
            
            try
            {
                // 查询当天最大序号
                var query = await _procurementwarehousingRepository.GetQueryableAsync();
                var todayMaxCode = query
                    .Where(x => x.LnboundCode.StartsWith(prefix))
                    .OrderByDescending(x => x.LnboundCode)
                    .FirstOrDefault()?.LnboundCode;

                int sequence = 1;
                if (!string.IsNullOrEmpty(todayMaxCode) && todayMaxCode.Length == prefix.Length + 6)
                {
                    var sequenceStr = todayMaxCode.Substring(prefix.Length);
                    if (int.TryParse(sequenceStr, out int currentSequence))
                    {
                        sequence = currentSequence + 1;
                    }
                }

                return $"{prefix}{sequence:D6}";
            }
            catch
            {
                // 如果查询失败，返回默认序号
                return $"{prefix}000001";
            }
        }

        /// <summary>
        /// 生成入库单编号 (同步版本)
        /// </summary>
        /// <returns>入库单编号</returns>
        public string GenerateInboundCode()
        {
            return GenerateInboundCodeAsync().Result;
        }
    }
}
